//
//  RegisterViewController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/29.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterInfoController.h"

@interface RegisterViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *mobileTextField;
@property (strong, nonatomic) IBOutlet UITextField *codeTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UITextField *againPasswordTextField;
@property (strong, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (assign, nonatomic) NSInteger captchaCount;
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    [self addBackButton];
    
    self.image1.layer.cornerRadius = self.image2.layer.cornerRadius = self.image3.layer.cornerRadius = self.image4.layer.cornerRadius = self.finshButton.layer.cornerRadius = 5.0f;
    self.image1.layer.masksToBounds = self.image2.layer.masksToBounds = self.image3.layer.masksToBounds = self.image4.layer.masksToBounds = self.finshButton.layer.masksToBounds = YES;
    self.passwordTextField.delegate = self;
    self.againPasswordTextField.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    self.captchaCount = 60;
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [self changeViewFrameWithKeyBoardNotification:notification isShow:NO];
}

- (void)changeViewFrameWithKeyBoardNotification:(NSNotification *)notification isShow:(BOOL)isShow
{
    NSDictionary *userInfo = [notification userInfo];
    NSNumber *animationDur = userInfo[UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *animationCur = userInfo[UIKeyboardAnimationCurveUserInfoKey];
    
    [UIView beginAnimations:@"changeViewFrame" context:nil];
    [UIView setAnimationCurve:[animationCur integerValue]];
    [UIView setAnimationDuration:[animationDur doubleValue]];
    [self.view setFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
    [UIView commitAnimations];
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
        NSTimeInterval animationDuration=0.30f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
         [UIView setAnimationDuration:animationDuration];
         float width = self.view.frame.size.width;
          float height = self.view.frame.size.height;
    if (ScreenHeight == 480) {
        //上移n个单位，按实际情况设置
        CGRect rect=CGRectMake(0.0f,-30,width,height);
        self.view.frame=rect;
        [UIView commitAnimations];
    } else if (ScreenHeight == 568) {
        //上移n个单位，按实际情况设置
        CGRect rect=CGRectMake(0.0f,-10,width,height);
        self.view.frame=rect;
        [UIView commitAnimations];
    } else {
        //上移n个单位，按实际情况设置
        CGRect rect=CGRectMake(0.0f,0.0f,width,height);
        self.view.frame=rect;
        [UIView commitAnimations];
    }
          return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.mobileTextField resignFirstResponder];
    [self.codeTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    [self.againPasswordTextField resignFirstResponder];
}

// 获取验证码按钮
- (IBAction)getCodeButtonAction:(UIButton *)sender {
    NSDictionary *dic = [[NSDictionary alloc]init];
    dic = @{@"mobile":self.mobileTextField.text};
    BOOL isMatchTwo = [self isValidateMobile:self.mobileTextField.text];
    
    if ([self.mobileTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码！"];
    }else if (!isMatchTwo || self.mobileTextField.text.length <11)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码！"];
    }else
    {
        [HttpRequestManager getMethod:[NSString stringWithFormat:@"http://www.wplink.cn/index.php?g=Wap&m=Washcar&a=api_employee_get_code&mobile=%@",self.mobileTextField.text] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            NSLog(@"%@----------------",response);
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeCodeTime) userInfo:nil repeats:YES];
            if ([response[@"status"] isEqualToNumber:@1])
            {
                [SVProgressHUD showSuccessWithStatus:@"验证码发送成功！"];
                self.getCodeBtn.enabled = NO;
            }else if([response[@"status"] isEqualToNumber:@0])
            {
                [SVProgressHUD showErrorWithStatus:@"60秒内不能重复发送！"];
            }else{
                [SVProgressHUD showErrorWithStatus:@"验证码发送失败！"];
            }
            
        }];
    }
    
}

- (void)changeCodeTime
{
    if (self.captchaCount == 0) {
        self.getCodeBtn.enabled = YES;
        [self.timer invalidate];
        [self.getCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        self.captchaCount = 60;
    }else{
        self.captchaCount = self.captchaCount - 1;
        NSString *lostTime = [NSString stringWithFormat:@"%lds",(long)self.captchaCount];
        [self.getCodeBtn setTitle:lostTime forState:UIControlStateNormal];
    }
}

-(BOOL) isValidateMobile:(NSString *)mobile
{
    if (mobile.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobile] == YES)
        || ([regextestcm evaluateWithObject:mobile] == YES)
        || ([regextestct evaluateWithObject:mobile] == YES)
        || ([regextestcu evaluateWithObject:mobile] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }

}


// 下一步按钮
- (IBAction)finshButtonAction:(UIButton *)sender {
    BOOL isMatchTwo = [self isValidateMobile:self.mobileTextField.text];
    if ([self.mobileTextField.text isEqual:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码！"];
    }else if (!isMatchTwo || self.mobileTextField.text.length <11)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码！"];
    }
    else if ([self.codeTextField.text isEqual:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码！"];
    }else if ([self.passwordTextField.text isEqual:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入密码！"];
    }
    else if ([self.againPasswordTextField.text isEqual:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请再次输入密码！"];
    }else if (![self.againPasswordTextField.text isEqualToString:self.passwordTextField.text])
    {
        [SVProgressHUD showErrorWithStatus:@"两次密码不一致"];
    }else
    {
        [self webRequest_Login:self.mobileTextField.text setpassword:self.passwordTextField.text confirmpassword:self.againPasswordTextField.text smscode:self.codeTextField.text];
    }
}

- (void)webRequest_Login:(NSString *)username setpassword:(NSString *)password confirmpassword:(NSString *)againpassword smscode:(NSString *)code
{
    [self.mobileTextField resignFirstResponder];
    [self.codeTextField resignFirstResponder];
    NSDictionary *dict =  @{@"mobile":username,@"password":password,@"confirmpassword":againpassword,@"smscode":code};
    [HttpRequestManager getMethod:KRegisterInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            [[NSUserDefaults standardUserDefaults]setObject:response[@"uid"] forKey:KUserDefaultsUserIdKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            RegisterInfoController *registerVC = [[RegisterInfoController alloc]init];
            [self.navigationController pushViewController:registerVC animated:YES];
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"注册失败"];
        }
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
